'''
    项目名称:英雄联盟皮肤爬虫
    项目说明:向英雄联盟官网发送请求,获取英雄皮肤
    项目环境:pycharm
    项目所属:会飞的男孩
'''

import json
import requests
import os

class lolskin():
    def __init__(self):
        self.url = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?'
        self.header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                          'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Safari/537.36'
        }

    def get_heroId(self, url, header):
        res = requests.get(url, headers=header).json()['hero']
        # print(res)
        heroId_list =[]
        for i in res:
            heroId_list.append([i['heroId'],i['name']])
        return heroId_list
    def get_hero_skin(self, url_id, header,hero):

        url = f'https://game.gtimg.cn/images/lol/act/img/js/hero/{url_id}.js?'
        res = requests.get(url, headers=header).json()['skins']
        # print(res)
        for i in res:
            if i['mainImg']:
                # print(i['mainImg'])
                self.save_skin(i['mainImg'],self.header,hero,i['name'])


    def save_skin(self,url,header,hero,skin):
        print(f'正在下载{hero}皮肤')
        res= requests.get(url,headers=header)
        path = os.path.join('lol',hero)
        os.makedirs(path, exist_ok=True)
        file = os.path.join(path, f'{skin}.jpg')
        with open(file,'wb') as f:
            f.write(res.content)
        print('下载完成')



    def run(self):
        id_hero= self.get_heroId(self.url, self.header)
        for i in id_hero:
            self.get_hero_skin(i[0], self.header,i[1])


if __name__ == '__main__':
    lol = lolskin()
    lol.run()
